<?php
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($id <= 0) {
    echo json_encode([
        'status' => 'error',
        'message' => '无效的指南ID'
    ]);
    exit;
}

try {
    // 更新浏览次数
    $update_sql = "UPDATE fitness_guides SET views = views + 1 WHERE id = ?";
    $update_stmt = $conn->prepare($update_sql);
    $update_stmt->bind_param("i", $id);
    $update_stmt->execute();
    
    // 获取指南详情
    $sql = "SELECT * FROM fitness_guides WHERE id = ? AND status = 1";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $guide = $result->fetch_assoc();
        // 格式化时间
        $guide['create_time'] = date('Y-m-d H:i', strtotime($guide['create_time']));
        
        // 查询收藏状态
        $user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
        if ($user_id > 0) {
            $fav_sql = "SELECT id FROM favorites WHERE user_id = ? AND guide_id = ?";
            $fav_stmt = $conn->prepare($fav_sql);
            $fav_stmt->bind_param("ii", $user_id, $id);
            $fav_stmt->execute();
            $fav_result = $fav_stmt->get_result();
            $guide['is_favorite'] = $fav_result->num_rows > 0;
            $fav_stmt->close();
        }
        
        echo json_encode([
            'status' => 'success',
            'guide' => $guide
        ]);
    } else {
        throw new Exception("指南不存在");
    }

} catch (Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
} finally {
    if (isset($stmt)) $stmt->close();
    if (isset($update_stmt)) $update_stmt->close();
    $conn->close();
}
?> 